<?php
require __DIR__ . '/../../bootstrap.php';
$em = require __DIR__ . '/../../example/em.php';
use Service\SimManager;

# include parseCSV class.
require_once('parsecsv/parsecsv.lib.php');


$_POST['file'] = '../../uploads/07-07-2013_19-52-32.csv';
$file = $_POST['file'];

# create new parseCSV object.
$csv = new parseCSV();
$csv->heading = 0;
//print_r($csv);
# Parse '_books.csv' using automatic delimiter detection...
$csv->auto($file);
?>

    <!DOCTYPE HTML>
    <html>
    <head>
        <meta http-equiv="content-type" content="text/html" charset=utf-8/>
        <title>' . $file . '</title>
        <style type="text/css" media="screen">
            table {
                background-color: #BBB;
            }

            th {
                background-color: #EEE;
            }

            td {
                background-color: #FFF;
            }

            .error {
                background-color: #ff0000;
            }

            tr {
                display: table-row;
            }

            td, th {
                display: table-cell;
            }
        </style>
    </head>

    <body>
    <table border="0" cellspacing="1" cellpadding="3">
        <tr>
            <th>Номер</th>
            <th>ICCID</th>
            <th>Номер подписан</th>
            <th>Номер создан</th>
            <th>Такой номер уже существует</th>
        </tr>
        <?php
        foreach ($csv->data as $key => $row) {
            $_POST['create_sim_number'] = $row[0];
            if (!isset($row[1])) {
                $_POST['create_sim_puk'] = 0;
            } else {
                $_POST['create_sim_puk'] = $row[1];
            }
            $sim = array('number' => $_POST['create_sim_number'], 'puk' => $_POST['create_sim_puk']);
            $manager = new SimManager($em);
            if (!$manager->isValidPhoneNumber($sim['number'])) {
                echo '<tr>';
                echo '<td>' . $row[0] . '</td>';
                echo '<td>' . $row[1] . '</td>';
                echo '<td></td>';
                echo '<td></td >';
                echo '<td class="error" >Y</td>';
                echo '</tr>';
            } else {
                $phone_number = $sim['number'];
                $url = urlencode('http://agent.smart-sim.ru/ajax/podpiska.php');
                $response = check($phone_number, $url, $manager, $sim, $response = array());
                echo '<tr>';
                echo '<td>' . $row[0] . '</td>';
                echo '<td>' . $row[1] . '</td>';
                echo '<td class="' . $response['info']['class'] . '">' . $response['info']['message'] . '</td>';
                echo '<td></td >';
                echo '<td></td>';
                echo '</tr>';
            }
        }
        ?>
    </table>
    </body>
    </html>
<?php
exit();
// открываем файл, если файл не существует,
//делается попытка создать его
$fp = fopen("../../uploads/file.html", "w");

// записываем в файл текст
$html = $header_html . $body_html . $footer_html;
fwrite($fp, $html);

// закрываем
fclose($fp);

////////////////////////////////////

//https://service.smart-sim.ru:443/api/37282879541/updates?uname=paul&upass=kam9345t&url=http%3A%2F%2Fagent.smart-sim.ru%2Fajax%2Fpodpiska.php

//check($phone_number, $url, $manager, $sim);

function check($phone_number, $url, $manager, $sim, $response)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://service.smart-sim.ru:443/api/" . $phone_number . "/updates?uname=paul&upass=kam9345t&url=" . $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "");
//    curl_setopt($ch, CURLOPT_INTERFACE, "192.168.1.104");
    curl_setopt($ch, CURLOPT_INTERFACE, "88.196.96.108");

    $result = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);


    if ($info['http_code'] != 200) {
        $response['info']['message'] = "Ошибка! HTTP: " . $info['http_code'] . " Проблемы с сервером.";
        $response['info']['class'] = "error";
        return $response;
        exit();
    } else {
        //print_r($info['http_code']);
        $xml = simplexml_load_string($result);

        //echo '<pre>';
        //print_r($xml);
        //echo '</pre>';

        if ($xml['success'] == true) {
            $manager->create($sim);
            //echo '{ "message": "Создан и подписан номер ' . $_POST['create_sim_number'] . '. Ответ сервера: ' . $info['http_code'] . '", "type": "st-success" }';
            $response['info']['message']='';
            $response['info']['class'] = '';
        }

        if ($xml->attributes()->error == 1) {
            $response['info']['message']='Ошибка! '. $xml->error;
            $response['info']['class'] = "error";
            echo '{ "message": "Ошибка! ' . $xml->error . '", "type": "st-error" }';
        }
    }
}


####################################


# ...or if you know the delimiter, set the delimiter character
# if its not the default comma...
// $csv->delimiter = "\t";   # tab delimited
//$csv->delimiter = ";";   # tab delimited
# ...and then use the parse() function.
// $csv->parse('_books.csv');


# Output result.
//$csv->parse('../../uploads/01-07-2013_15-00-04.csv');
//print_r($csv->data);


?>